<!-- 父级页面:控制除登录页以外的所有页面共有的头部与左侧菜单栏 -->
<template>
  <!-- display: flex;表示给父元素使用弹性布局
   效果:所有子元素横置,且父元素会根据子元素横置后的实际高度自动填充高度 -->
  <div style="display: flex;">
    <!-- isCollapse值为true,折叠左侧菜单栏,宽度为64px,不折叠时宽度为208px   -->
    <div :style="{width:( isCollapse ? '64px' : '208px' )}">
      <!-- 左侧菜单栏
      unique-opened只允许打开一个菜单项  router允许菜单项进行路由跳转 -->
      <el-menu
          background-color="#000"
          text-color="#fff"
          active-text-color="#ff0"
          style="width: 100%;height: 100vh;"
          :collapse="isCollapse"
          :collapse-transition="false"
          router unique-opened
          @select="selectMenu"
      >
        <!-- 左侧菜单栏的顶部条 -->
        <el-row style="padding-top: 10px;">
          <el-col :span="2"></el-col>
          <el-col :span="7" style="padding-left:7px;">
            <el-avatar src="/imgs/admin/logo.png" style="width: 35px;height: 35px;"></el-avatar>
          </el-col>
          <el-col :span="isCollapse ? 0 : 13">
            <span style="color:#fff;font-weight: bold;position:relative;top:8px;left:2px;">小霸王</span>
          </el-col>
        </el-row>
        <el-sub-menu index="1">
          <template #title>
            <el-icon style="font-size: 21px;"><User/></el-icon> <span>工作台</span>
          </template>
          <el-menu-item index="/homeDisplay">工作台</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="2">
          <template #title>
            <el-icon style="font-size: 21px;"><Van/></el-icon> <span>基础数据</span>
          </template>
          <el-menu-item index="/basicInformation">基础信息</el-menu-item>
          <el-menu-item index="/approvalProcess">审批流程</el-menu-item>
          <el-menu-item index="/reimbursementType">报销类型</el-menu-item>
          <el-menu-item index="/expenseType">费用类型</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="3">
          <template #title>
            <el-icon style="font-size: 21px;"><Location/></el-icon> <span>人力资源</span>
          </template>
          <el-menu-item index="/departmentStructure">部门架构</el-menu-item>
          <el-menu-item index="/employees">企业员工</el-menu-item>
          <el-menu-item index="/exitFile">离职档案</el-menu-item>
          <el-menu-item index="/personTransfers">人事调动</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="4">
          <template #title>
            <el-icon style="font-size: 21px;"><Place/></el-icon> <span>行政管理</span>
          </template>
          <el-menu-item index="/sealManagement">印章管理</el-menu-item>
          <el-menu-item index="/vehicleManagement">车辆管理</el-menu-item>
          <el-menu-item index="/roomManagement">会议室管理</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="5">
          <template #title>
            <el-icon style="font-size: 21px;"><MessageBox/></el-icon> <span>财务管理</span>
          </template>
          <el-menu-item index="/reimbursementManagement">报销管理</el-menu-item>
          <el-menu-item index="/reimbursementPayments">报销打款 </el-menu-item>
          <el-menu-item index="/invoiceManagement">发票管理</el-menu-item>
          <el-menu-item index="/invoicing">发票开票</el-menu-item>
          <el-menu-item index="/invoicesArrived">发票到账</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="6">
          <template #title>
            <el-icon style="font-size: 21px;"><Place/></el-icon> <span>企业公告</span>
          </template>
          <el-menu-item index="/announcementsList">公告列表</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="7">
          <template #title>
            <el-icon style="font-size: 21px;"><Place/></el-icon> <span>办公审批</span>
          </template>
          <el-menu-item index="/initiated">我发起的</el-menu-item>
          <el-menu-item index="/dealtWith">我抄送的</el-menu-item>
          <el-menu-item index="/ccedToMe">抄送给我的</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="8">
          <template #title>
            <el-icon style="font-size: 21px;"><MessageBox/></el-icon> <span>日常办公</span>
          </template>
          <el-menu-item index="/calendarEvents">日程日历</el-menu-item>
          <el-menu-item index="/workRecords">工作记录</el-menu-item>
          <el-menu-item index="/workCalendar">工作日历</el-menu-item>
          <el-menu-item index="/debriefing">工作汇报</el-menu-item>
          <el-menu-item index="/schedule">日程安排</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="9">
          <template #title>
            <el-icon style="font-size: 21px;"><MessageBox/></el-icon> <span>客户管理</span>
          </template>
          <el-menu-item index="/customerLists">客户列表</el-menu-item>
          <el-menu-item index="/customerContacts">客户联系人</el-menu-item>
          <el-menu-item index="/salesOpportunities">销售机会</el-menu-item>
          <el-menu-item index="/followUpRecords">跟进记录</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="10">
          <template #title>
            <el-icon style="font-size: 21px;"><MessageBox/></el-icon> <span>合同管理</span>
          </template>
          <el-menu-item index="/contractCategory">合同类别</el-menu-item>
          <el-menu-item index="/contractsList">合同列表</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="11">
          <template #title>
            <el-icon style="font-size: 21px;"><MessageBox/></el-icon> <span>项目管理</span>
          </template>
          <el-menu-item index="/itemsList">项目列表 </el-menu-item>
          <el-menu-item index="/taskList">任务列表</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="12">
          <template #title>
            <el-icon style="font-size: 21px;"><MessageBox/></el-icon> <span>系统管理</span>
          </template>
          <el-menu-item index="/functionalNodes">功能节点</el-menu-item>
          <el-menu-item index="/rolePermissions">角色权限</el-menu-item>
          <el-menu-item index="/dataPermissions">数据权限</el-menu-item>
          <el-menu-item index="/operationLogs">操作日志</el-menu-item>
        </el-sub-menu>
        <el-sub-menu index="13">
          <template #title>
            <el-icon style="font-size: 21px;"><MessageBox/></el-icon> <span>数据字典</span>
          </template>
          <el-menu-item index="/dict">字典管理</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>
    <!-- 右侧始终为100%减去左侧菜单栏的宽度  -->
    <div :style="{width:( isCollapse ? 'calc(100% - 64px)' : 'calc(100% - 208px)' )}">
      <!-- 右侧顶部条与主体内容 -->
      <el-header style="height:10vh;background-color:#fff;padding-top:22px;">
        <!-- 折叠图标与用户名选项 -->
        <el-row :gutter="10">
          <el-col :span="18">
            <el-icon style="font-size:20px;" @click="changeCollapse"><Expand/></el-icon>
          </el-col>
          <el-col :span="6" style="position:relative;">
            <el-dropdown trigger="click" style="position: absolute;right:20px;">
              <span style="font-size:30px;font-weight:bold;">
                {{user.username}}
                <el-icon style="color: dodgerblue; cursor: pointer;"><UserFilled /></el-icon>
                <p style="font-size:12px;font-weight:bold;">在线时长：{{formattedDuration}}</p>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/" style="position:relative;top:20px;">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item v-for="item in breadcrumb">{{item}}</el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>
      <el-main style="height:90vh;padding:0;overflow-y: auto;">
        <router-view/>
      </el-main>
    </div>
  </div>
</template>

<script setup>
import {computed, onBeforeUnmount, onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
//定义变量控制左侧菜单栏是否折叠
const isCollapse = ref(false);
const changeCollapse = () => {
  isCollapse.value = !isCollapse.value;
};
let timer;

const user = ref(getUser());
const logout = async () => {
  if (confirm("您确认要退出登录吗?")) {
    const data = qs.stringify({
      id: user.value.id,
      duration: onlineDuration.value
    })
    await axios.post(BASE_URL + '/oa1/user/onlineDuration', data)
        .then((response) => {
          console.log(response);
          ElMessage.success(response.data.msg);
          // 清除localStorage中存储的数据
          localStorage.removeItem('user');
          localStorage.removeItem('breadCrumb');
          window.location.href = "/login";
          user.value = '';

        })
  }
}


//定义维护菜单项index与面包屑导航的对应关系
let map = {
  '/basicInformation': ['基础数据','基础信息'],
  '/approvalProcess': ['基础数据','审批流程'],
  '/reimbursementType': ['基础数据','报销类型'],
  '/expenseType': ['基础数据','费用类型'],
  '/departmentStructure': ['人力资源','部门架构'],
  '/employees': ['人力资源','企业员工'],
  '/exitFile': ['人力资源','离职档案'],
  '/personTransfers': ['人力资源','人事调动'],
  '/sealManagement': ['行政管理','印章管理'],
  '/vehicleManagement': ['行政管理','车辆管理'],
  '/roomManagement': ['行政管理','会议室管理'],
  '/reimbursementManagement': ['财务管理','报销管理'],
  '/reimbursementPayments': ['财务管理','报销打款'],
  '/invoiceManagement': ['财务管理','发票管理'],
  '/invoicing': ['财务管理','发票开票'],
  '/invoicesArrived': ['财务管理','发票到账'],
  '/announcementsList': ['企业公告','公告列表'],
  '/initiated': ['办公审批','我发起的'],
  '/dealtWith': ['办公审批','我抄送的'],
  '/ccedToMe': ['办公审批','抄送给我的'],
  '/schedule': ['日常办公','日程安排'],
  '/calendarEvents': ['日常办公','日程日历'],
  '/workRecords': ['日常办公','工作记录'],
  '/workCalendar': ['日常办公','工作日历'],
  '/debriefing': ['日常办公','工作汇报'],
  '/customerLists': ['客户管理','客户列表'],
  '/customerContacts': ['客户管理','客户联系人'],
  '/salesOpportunities': ['客户管理','销售机会'],
  '/followUpRecords': ['客户管理','跟进记录'],
  '/contractCategory': ['数据字典','合同类别'],
  '/contractsLis': ['数据字典','合同列表'],
  '/itemsList': ['项目管理','项目列表 '],
  '/taskList': ['项目管理','任务列表'],
  '/rolePermissions': ['系统管理','角色权限'],
  '/dataPermissions': ['系统管理','数据权限'],
  '/operationLogs': ['系统管理','操作日志'],
  '/dict': ['数据字典','字典管理'],
  '/functionalNodes': ['系统管理','功能节点'],
};
//定义一个变量用来保存当前面包屑导航值
//先到localStorage中获取面包屑的值,没有才使用默认值['用户管理','用户列表']
const breadcrumb = ref(JSON.parse(localStorage.getItem('breadCrumb'))
    || ['用户管理','用户列表']);
//定义函数,只要选择了菜单的某一个菜单项,就可以立即获取当前菜单项的index值
const selectMenu = (index)=>{
  breadcrumb.value = map[index];//等价于java的 map.get('index')=>['调度管理','车辆分配']
  //解决面包屑值刷新页面丢失的问题:每次选择完菜单项,将面包屑的值也随之更新到localStorage中
  localStorage.setItem('breadCrumb',JSON.stringify(breadcrumb.value));
}
const onlineDuration = ref(parseInt(localStorage.getItem('onlineDuration')) || 0);

const startTimer = () => {
  timer = setInterval(() => {
    onlineDuration.value += 1;
    localStorage.setItem('onlineDuration', onlineDuration.value.toString());
  }, 1000);
};

const stopTimer = () => {
  clearInterval(timer);
};

const formattedDuration = computed(() => {
  const hours = Math.floor(onlineDuration.value / 3600);
  const minutes = Math.floor((onlineDuration.value % 3600) / 60);
  const seconds = onlineDuration.value % 60;
  return `${hours} 小时 ${minutes} 分 ${seconds} 秒`;
});

onMounted(() => {
  startTimer();
  window.addEventListener('beforeunload', stopTimer);
});

onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', stopTimer);
  stopTimer();
});
</script>